<template>
	<tn-sticky>
		<!-- 子视图：用于放置底部导航栏和其他组件 -->
		<view style="width: 100%; height: 50px; margin-top: 15%;">
			<!-- 底部导航栏 -->
			<tn-tabbar v-model="currentTabIndex" :list="tabbarItems" :fixed="false" bgColor="#008080" :fontSize="30"
				activeColor="#ffffff" @change="onTabChange" :beforeSwitch="beforeTabSwitch">
			</tn-tabbar>
		</view>
		<tn-toast ref="toast" />

		<!-- 弹窗视图 -->
		<view>
			<tn-popup v-model="isPopupVisible" mode="top" height="80%" :marginTop="80" :closeBtn="true"
				closeBtnIcon="close-circle" :closeIconSize="50" @close="closed">
				<form @touchmove.prevent>
					<!-- 弹窗顶部按钮和内容 -->
					<view style="color: #000; margin-top: 3%; text-align: right; margin-right: 13%;">
						<tn-button backgroundColor="#008080" fontColor="#ffffff" @click="dian"
							style="margin-right: 60%;" :blockRepeatClick="true">发布</tn-button>
						发呆滞
					</view>

					<!-- 弹窗输入和图片上传 -->
					<view style="margin-left: 10%; width: 80%; margin-top: 5%; border-radius: 10px;">
						<view style="display: flex;align-items: center;">
							<text style="color: #000;">商品名称：</text>
							<tn-input style="border: 1px solid #23e5be;border-radius: 25px;padding-left: 5px;"
								v-model="form.name" :clearable="false"></tn-input>
						</view>
						<text style="color: #000;">
							描述：
						</text>
						<tn-input v-model="form.brief" type="textarea" placeholder="请输入" :height="150"
							style="padding-left: 5px;" :clearable="false" />
						<tn-image-upload :action="action" ref="imageUpload" :maxCount="1" />
						<tn-button :border="false" padding="0 0rpx" @click="fetchLocation"><text
								class="tn-icon-location"
								style="margin-bottom: 2px;margin-right: 5px;" />{{form.locationCity}}</tn-button>
					</view>
					<view style="width: 80%;height: 6%;color: #000;margin-left: 10% ;display:flex;align-items:center;">
						请选择类目:<br />{{form.category.name}}
						<tn-button @click="CategorysShow=true" :border="true"
							style="border: 1px solid powderblue;margin-left: auto">请选择类目</tn-button>
					</view>
					<!-- 弹窗底部价格和发货方式 -->
					<view style="color: black; width: 80%; margin-left: 10%; height: 20%">
						<view style="height: 40px;display: flex;align-items:center">
							<text>价格:￥</text>
							<tn-input v-model="form.counterPrice" placeholder="请输入价格" placeholderStyle="color:#ff3c01"
								:clearable="false" style="width: auto;margin-left: 11px;" type="number" />
						</view>
						<view style="height: 40px;display: flex;align-items:center">
							<text>库存:</text>
							<tn-input v-model="form.products" placeholder="请输入库存" placeholderStyle="color:#ff3c01"
								:clearable="false" style="width: auto;margin-left: 15px;" type="number" />
						</view>
						<view style="margin-top: 3%; height: 50px;display: flex;align-items:center;">
							发货方式：{{form.delivery===1?"包邮":"买家自费"}}
							<tn-button @click="show=true" :border="true"
								style="border: 1px solid powderblue;margin-left: auto">选择发货方式</tn-button>
							<tn-select v-model="show" mode="single" :list="list" @confirm="confirm" />
						</view>
					</view>
				</form>
				<tn-toast ref="toast"></tn-toast>
				<tn-popup v-model="CategorysShow" mode="bottom" style="">
					<view style="width: 100%;height: auto;" @touchmove.prevent>
						<tn-button v-for="(tab) in CategoryList" :key="tab.id"
							style="border: 1px solid black; margin: 2px;"
							@click="form.category=tab,CategorysShow=false">{{tab.name}}</tn-button>
					</view>
				</tn-popup>
			</tn-popup>
		</view>
	</tn-sticky>
</template>

<script>
	import {
		v4 as uuidv4
	} from 'uuid'
	export default {
		props: {
			// props接收：定义父组件传递的当前索引
			currentIndex: {
				type: Number
			}
		},
		name: "tTabbar",

		data() {
			return {
				timeoutId: undefined,
				form: {
					name: "",
					brief: "",
					picUrl: "",
					counterPrice: "",
					delivery: 1,
					goodsSn: "",
					category: {
						id: 0,
						name: ""
					},
					locationCity: "请选择商品所在地",
					userId: uni.getStorageSync("userInfo").id,
					products: ""
				},
				CategorysShow: false,
				CategoryList: [],
				show: false,
				list: [{
						value: 1,
						label: '包邮'
					},
					{
						value: 2,
						label: '买家自费'
					}
				],
				currentTabIndex: this.currentIndex, // 当前选择的Tab索引
				isPopupVisible: false, // 控制弹窗显示
				tabbarItems: [ // tabbar配置项
					{
						title: '首页',
						activeIcon: 'home-fill',
						inactiveIcon: 'home'
					},
					{
						title: "附近",
						activeIcon: 'map-fill',
						inactiveIcon: 'map'
					},
					{
						title: '卖',
						activeIcon: 'commissary-fill',
						inactiveIcon: 'commissary',
						activeIconColor: '#FFFFFF',
						inactiveIconColor: '#FFFFFF',
						iconSize: 50,
						out: true
					},
					{
						title: '消息',
						activeIcon: 'message-fill',
						inactiveIcon: 'message'
					},
					{
						title: '我的',
						activeIcon: 'my-fill',
						inactiveIcon: 'my'
					}
				],
				action: this.baseUrl + "/admin/storage/create"
			};
		},
		// 生命周期函数：页面加载时隐藏Uni的原生tabbar
		onLoad() {
			uni.hideTabBar();
		},
		mounted() {
			this.getCategoryList()
			this.fetchLocation()
		},
		methods: {
			closed() {
				this.form = {
					name: "",
					brief: "",
					picUrl: "",
					counterPrice: "",
					delivery: 1,
					goodsSn: "",
					category: {
						id: 0,
						name: ""
					},
					locationCity: "请选择商品所在地",
					userId: 0,
					products: 0
				}
				this.isPopupVisible = false
			},

			dian() {
				let files = []
				files = this.$refs.imageUpload.lists.filter(val => {
					return val.progress == 100
				})
				

				if (this.form.name === "") {
					this.$refs.toast.show({
						content: "商品名称未填写",
						duration: 1000
					})
					return
				}
				if (this.form.counterPrice === "") {
					this.$refs.toast.show({
						content: "商品价格未填写",
						duration: 1000
					})
					return
				}
				if (files.length === 0) {
					this.$refs.toast.show({
						content: "商品图片缺失",
						duration: 1000
					})
					return
				} else {
					this.form.picUrl = files[0].response.data
				}
				if (this.form.category.id === 0) {
					this.$refs.toast.show({
						content: "类目未选择",
						duration: 1000
					})
					return
				}
				if (this.form.locationCity === "请选择商品所在地") {
					this.$refs.toast.show({
						content: "请选择商品所在地",
						duration: 1000
					})
					return
				}
				this.form.goodsSn = uuidv4()
				this.submit()
			},
			confirm(e) {
				this.show = false
				this.form.delivery = e[0].value
			},
			// beforeSwitch事件：判断某些Tab是否可切换
			beforeTabSwitch(index) {
				if (index === 2 || index === 3) {
					clearTimeout(this.timeoutId);
					let userInfo = uni.getStorageSync("userInfo");
					if (userInfo.id != undefined && userInfo.id != 0) {
						if (index === 2) {
							this.isPopupVisible = true; // 显示弹窗
						} else {
							return true
						}
					} else {
						uni.showToast({
							title: "还未登录，请登录后重试",
							icon: "none",
						});
						this.timeoutId = setTimeout(function() {
							uni.navigateTo({
								url: "/pages/Information/login/login"
							})
						}, 1500)
					}
					return false; // 禁止切换
				} else {
					return true; // 允许切换
				}
			},
			getCategoryList() {
				let that = this
				that.form.userId = uni.getStorageSync("userInfo").id
				uni.request({
					url: this.baseUrl + "/admin/category/list",
					success: function(res) {
						let list = res.data.data.list.filter(item => (item.id === 1036065))
						let children = list[0].children
						that.CategoryList = children
					},
					fail(e) {
						console.error('获取分类列表请求失败：', e)
						that.CategoryList = [] // 请求失败时设置空数组
						uni.showToast({
							title: '获取分类失败',
							icon: 'none'
						})
					}
				})
			},

			// 切换tabbar时触发的回调
			onTabChange(index) {
				if (this.currentTabIndex != index) {
					this.currentTabIndex = index;
					// 索引与页面路径的映射关系
					const urlMap = {
						0: '/pages/index/index',
						1: '/pages/area/area',
						3: '/pages/message/messageList',
						4: '/pages/Information/Information'
					};
					// 获取对应路径，默认为首页路径
					const targetUrl = urlMap[index];
					// 跳转到指定路径
					uni.redirectTo({
						url: targetUrl,
						animationType: "none"
					});
				}
			},
			submit() {
				let that = this
				that.form.userId = uni.getStorageSync("userInfo").id
				uni.request({
					url: this.baseUrl + "/admin/goods/create",
					method: "POST",
					sslVerify: false,
					data: {
						goods: {
							picUrl: this.form.picUrl,
							gallery: [],
							isHot: false,
							isNew: true,
							isOnSale: true,
							goodsSn: that.form.goodsSn,
							name: that.form.name,
							counterPrice: that.form.counterPrice,
							categoryId: that.form.category.id,
							brief: that.form.brief
						},
						specifications: [{
							specification: "规格",
							value: "标准",
							picUrl: ""
						}],
						products: [{
							id: 0,
							"specifications": [
								"标准"
							],
							price: that.form.counterPrice,
							number: that.form.products,
							url: ""
						}],
						attributes: [{
							attribute: "delivery",
							value: that.form.delivery
						}, {
							attribute: "locationCity",
							value: that.form.locationCity
						}, {
							attribute: "userId",
							value: that.form.userId
						}]
					},
					success(res) {
						that.$refs.toast.show({
							content: "发布成功",
							duration: 2000
						})
						setTimeout(function() {
							that.isPopupVisible = false
							that.form = {
								name: "",
								brief: "",
								picUrl: "",
								counterPrice: "",
								delivery: 1,
								goodsSn: "",
								category: {},
								locationCity: "请选择商品所在地"
							}
						}, 2000)
					},
					fail(e) {
						console.log("添加商品请求" + e);
						that.$refs.toast.show({
							content: "发生错误，请联系管理员",
							duration: 2000
						})
					}
				})
			},
			fetchLocation() {
				let locationCity = uni.getStorageSync("locationCity")

				if (locationCity === "") {
					uni.getLocation({
						type: 'wgs84',
						geocode: true,
						success: this.onLocationFetchSuccess,
						fail: this.onLocationFetchFail
					});
				} else {
					this.form.locationCity = locationCity
				}
			},
			// 处理位置信息成功回调
			onLocationFetchSuccess(locationData) {
				const locationUrl = getApp().globalData.handleLocationUrl;
				const coordinates = `${locationData.longitude},${locationData.latitude}`;
				uni.request({
					url: `${locationUrl}${coordinates}`,
					method: 'GET',
					success: this.onAddressFetchSuccess,
					fail: this.onRequestFail
				});
			},
			// 处理获取地址成功回调
			onAddressFetchSuccess(response) {
				const address = response?.data?.regeocode?.addressComponent || {};
				this.position =
					`${address.province || ""} ${address.city || ""} ${address.district || ""}`.trim();
				let city = "";
				city = Array.isArray(address.city) ? (address.province || "未知城市") : address.city;
				this.form.locationCity = city;
				getApp().globalData.locationCity = city;
				uni.setStorageSync("locationCity", city);
			},
		}
	};
</script>

<style scoped>
	.tabbar-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.tabbar {
		display: flex;
		height: 100rpx;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.tabbar-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.tabbar-icon {
		width: 48rpx;
		height: 48rpx;
		margin-bottom: 4rpx;
	}

	.tabbar-text {
		font-size: 24rpx;
		color: #666666;
	}

	.tabbar-text.active {
		color: #ffffff;
	}

	.publish-form {
		padding: 30rpx;
		background: #ffffff;
		border-radius: 20rpx;
		width: 600rpx;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.form-item text {
		display: block;
		margin-bottom: 10rpx;
		color: #333333;
	}

	.form-item input,
	.form-item textarea {
		width: 100%;
		border: 1rpx solid #eeeeee;
		padding: 10rpx;
		border-radius: 8rpx;
	}

	.submit-btn {
		margin-top: 30rpx;
		background-color: #008080;
		color: #ffffff;
		border-radius: 8rpx;
	}
</style>